package org.grow.loginto.dao;

import com.querydsl.jpa.impl.JPAQueryFactory;
import org.grow.loginto.entity.*;
import org.grow.loginto.entity.QRoleInfo;
import org.grow.loginto.entity.QUserInfo;
import org.grow.loginto.entity.QUserRole;
import org.grow.loginto.exception.JulyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 21-6-2
 */
@Repository
public class UserInfoService implements UserDetailsService {

    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        System.out.println("loading...finding..."+s);
        UserInfo userInfo = userInfoDao.findByUsername(s);
        if (userInfo == null) throw new RuntimeException("用户名不存在");
//        System.out.println("found"+byUsername);
        QUserInfo u = QUserInfo.userInfo;
        QUserRole ur = QUserRole.userRole;
        QRoleInfo r = QRoleInfo.roleInfo;
//        userInfo.setAuthorities();
        List<RoleInfo> fetch = jpaQueryFactory.select(r)
                .from(u)
                .leftJoin(ur).on(u.userId.eq(ur.userFk))
                .leftJoin(r).on(ur.roleFk.eq(r.roleId))
                .where(u.username.eq(s))
                .fetch();
        if (fetch == null) throw new JulyException("当前用户没有任何角色配置",929);
        userInfo.setAuthorities(fetch);
                System.out.println("found"+userInfo);
        return userInfo;

    }

}
